import React,{PureComponent} from 'react';
import {connect} from 'dva';
import 'antd-mobile/lib/image-picker/style'
import {Modal,Carousel} from "antd-mobile"
import MToast from "../../Util/MToast"
import {isNull,getUUID,handleOSS} from "../../../utils/helper"
import {handleUrl,handleFile} from "../../../utils/request"
import co from "co";
class MyUploadImgOss extends PureComponent {
	constructor(props){
		super(props);
		let value = this.props.value;
		this.uploadInput = null;
		this.state = {
			value:value,
			previewVisible:false,
			previewImg:"",
			btnHide:false
		}
	}
	componentWillReceiveProps(nextProps){
		// Should be a controlled component.
		if('value' in nextProps){
			let value = nextProps.value;
			this.setState({
				value
			});
		}
	}
	changeValue=(val)=>{
		if(!('value' in this.props)){
			this.setState({
				value:val
			});
		}
		this.triggerChange(val);
	};
	triggerChange = (changedValue) =>{
		const onChange = this.props.onChange;
		if(onChange){
			onChange(changedValue);
		}
	};
	uploadFunc=(e)=>{
		this.setState({
			btnHide:false
		});
		let {dispatch,max_size,field,folder}=this.props;
		folder=isNull(folder)?"wb_file":folder;
		let uploadId = "upload_"+field[0];
		max_size=isNull(max_size)?5:max_size*1;
		let that=this;
		let files = e.target.files;
		let newFiles=[];
		for(let i=0;i<files.length;i++){
			let file = files[i];
			let size = file.size/(1024*1024);//kb
			if(size>max_size){
				MToast.fail(file.name+"文件过大，文件最大"+max_size+"Mb",1.5,null,false);
			}
			else{
				newFiles.push(file)
			}
		}
		files=newFiles; 
		//e.target.files是个数组 多选时 需要遍历 然后一个一个的上传
		OSS.urllib.request(handleUrl("auth/oss-sts") + "?token=" + localStorage[MI_APP_CODE+"mi_token"]+"&appid=" + MI_APP_CODE,{method:'POST'},(err,response) =>{
			let result;
			if(err){
				MToast.fail(err,1.5,null,false);
				return
			}
			try{
				result = JSON.parse(response).data
			}catch(e){
				MToast.fail('parse sts response info error: ' + e.message,1.5,null,false);
				return
			}
			let client = new OSS.Wrapper({
				accessKeyId:result.access_key_id,
				accessKeySecret:result.access_key_secret,
				stsToken:result.security_token,
				endpoint:'oss-cn-shanghai.aliyuncs.com',
				bucket:'mc-wb'
			});
			let len = files.length;
			let {max,value}=that.props;
			max=isNull(max)?5:max*1;
			let valLen=0;
			let isMax=false;
			if(isNull(value)){
				valLen=0;
			}
			else{
				valLen=value.split(",").length;
			}
			if(len>=max-valLen){
				len=max-valLen;
				isMax=true;
			}
			for(let i=0;i<len;i++){
				let file = files[i];
				let file_name = file.name;
				let suffix = file_name.substring(file_name.lastIndexOf("."),);
				co(function*(){
					let filePath = folder+"/"+getUUID() + suffix;
					let result = yield client.put(filePath,file);
					MToast.success(file_name+" uploaded successfully",1.5,null,false);
					console.log("result",result);
					let {name,url}=result;
					let {value}=that.state;
					if(isNull(value)){
						value = name;
					}
					else{
						value=value+","+name
					}
					that.changeValue(value);
					let dom = document.getElementById(uploadId);
					if(!isNull(dom)){
						dom.value=""
					}
				}).catch(function(err){
					MToast.fail(file_name+" file upload failed.",1.5,null,false);
					console.log(err);
				});
			}
			if(isMax){
				this.setState({
					btnHide:true
				});
				if(len>max-valLen){
					setTimeout(()=>{
						MToast.fail("最大上传: "+max+"，超出的未上传",1.5,null,false);
					})
				}
			}
		});
	};
	componentDidMount(){
		if(!isNull(this.uploadInput)){
			this.uploadInput.addEventListener("change",this.uploadFunc)
		}
	}
	
	onPreview=(file,isPdf)=>{
		if(isPdf){
			window.open(file,"_blank")
		}
		else{
			this.setState({
				previewVisible:true,
				previewImg:file
			})
		}
	};
	onRemove=(file)=>{
		// Modal.alert()
		let {value}=this.state;
		let val = value.split(",");
		val=val.filter(item=>item!==file);
		val=val.join(",");
		this.changeValue(val);
	};
	handleCancel = () =>{
		this.setState({
			previewVisible:false
		})
	};
	upload = () =>{
		this.uploadInput.click()
	};
	renderImg=(value,isDisabled,isReadonly)=>{
		if(isNull(value)||value.length==0){
			return null
		}
		else{
			console.log(value);
			value = value.split(",");
			let imgs=[];
			value.map((item,key)=>{
				let newItem=item;
				newItem=handleFile(newItem);
				let pdfIndex = newItem.indexOf(".pdf");
				let isPdf=false;
				if(pdfIndex!=-1){
					if((pdfIndex+4)===newItem.length){//是pdf
						isPdf=true
					}
				}
				imgs.push(
					<div className="mi-upload-img-img" key={newItem} onClick={()=>{
						this.setState({
							previewVisible:true,
							previewImg:handleOSS(item),
							previewIndex:key
						})
					}}>
						{
							!isDisabled&&!isReadonly&&<div className="am-image-picker-item-remove" onClick={(e)=>{
								e.preventDefault();
								e.stopPropagation();
								this.onRemove(item)
							}} >
								x
							</div>
						}
						<img src={isPdf?"image/pdf.jpg":newItem} />
						<span className="ant-upload-list-item-actions">
							<i className="anticon anticon-eye-o" onClick={()=>this.onPreview(newItem,isPdf)}/>
						</span>
					</div>
				)
			});
			return imgs
		}
	};
	render(){
		let {disabled,readonly,min=0,max=5,max_size=5,multiple=0,field,accept,tips}=this.props;
		accept=isNull(accept)?"image/*,application/pdf":accept;
		let uploadId ="upload_"+field[0];
		min=isNull(min)?0:min*1;
		max=isNull(max)?5:max*1;
		max_size=isNull(max_size)?5:max_size*1;
		let isMulti = multiple==1;
		let {previewVisible,previewImg,value,previewIndex,btnHide}=this.state;
		let isDisabled=disabled==1;
		let isReadonly=readonly==1;
		let uploadClass="clearfix mi-upload-img";
		if(isDisabled||isReadonly){
			uploadClass+=" disabled"
		}
		let imgLen=0;
		if(isNull(value)){
			imgLen=0
		}
		else{
			imgLen=value.split(",").length;
		}
		
		let isShowBtn = imgLen<max;
		isShowBtn=isShowBtn&&!isDisabled&&!isReadonly;
		if(btnHide&&isShowBtn){//按钮隐藏之后又出现了
			setTimeout(()=>{
				this.uploadInput.removeEventListener("change",this.uploadFunc,false);
				this.uploadInput.addEventListener("change",this.uploadFunc,false)
			})
		}
		return (
			<div className="am-image-picker" >
				<div className="am-image-picker-list" role="group">
					<div className="mi-upload-img-wrapper">
						{this.renderImg(value,isDisabled,isReadonly)}
						{
							isShowBtn?
								<div className="mi-upload-img-btn">
									<input
										id={uploadId}
										type="file"
										ref={e=>this.uploadInput=e}
										multiple={isMulti}
										accept="image/*" />
								</div>:null
						}
					</div>
				</div>
				<Modal
					visible={previewVisible}
					closable
					className="mi-upload-img-modal"
					onClose={()=>{
						this.setState({
							previewVisible:false
						})
					}}
				>
					<Carousel
						autoplay={false}
						infinite={false}
						selectedIndex={previewIndex}
					>
						{value&&value.split(",").map(val => (
							<a
								key={val}
								style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
							>
								<img
									src={`${handleOSS(val)}`}
									alt=""
									style={{ width: '100%', verticalAlign: 'center' }}
									onLoad={() => {
										// fire window resize event to change height
										window.dispatchEvent(new Event('resize'));
										this.setState({ imgHeight: 'auto' });
									}}
								/>
							</a>
						))}
					</Carousel>
				</Modal>
			</div>
		)
	}
}
export default MyUploadImgOss;